package spynx.util;

import java.lang.reflect.Constructor;
import java.util.regex.Pattern;

import spynx.desl.runtime.IExecutionContext;
import spynx.desl.runtime.IPatternMatchInfo;
import spynx.desl.runtime.IVariable;

public class DeslRuntimeUtil {
	
	public static IExecutionContext ActiveContext;
	
	public static Pattern compilePattern(IExecutionContext context, String text, int flag) {
		IExecutionContext root = context.getRootContext();
		String varName = "regex:" + Integer.toHexString(text.hashCode());
		IVariable var = root.Variables().getVariable(varName);
		if (var == null) 
			var = root.createVariable(varName, Pattern.compile(text, flag));
		return (Pattern) var.getValue();
	}

	public static IPatternMatchInfo getMatchInfo(IExecutionContext context) {
		return (IPatternMatchInfo) context.Variables().getVariable("@this");
	}
	
	public static void setMatchInfo(IExecutionContext context, IPatternMatchInfo matchInfo) {
		context.Variables().addVariable("@this", matchInfo);
	}
	
	public static Constructor<?> findConstructor(Class<?> clazz, Object...args) {
		Constructor<?> res = null;
		for (Constructor<?> ctor: clazz.getConstructors()) {
			Class<?>[] params = ctor.getParameterTypes();
			if (args.length == params.length) {
				boolean matched = true;
				for(int i = 0; i < args.length && matched; i++)
					matched = args[i] == null || params[i].isAssignableFrom(args[i].getClass());
				if (matched)
					return ctor;
			}
		}
		
		return res;
	}
}
